package ru.jexp.rcp.supply.swtext;

import org.eclipse.jface.dialogs.Dialog;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.jface.viewers.DoubleClickEvent;
import org.eclipse.jface.viewers.IDoubleClickListener;
import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Shell;

import ru.jexp.rcp.supply.img.JExpImageLink;
import ru.jexp.rcp.supply.mui.JExpSupplyMessages;
import ru.jexp.rcp.supply.swtext.factory.JExpLayoutFactory;
import ru.jexp.rcp.supply.viewer.JExpTableViewer;
import ru.jexp.rcp.supply.viewer.search.JExpSearchPanel;

public class JExpDialogLookup extends Dialog {

	private JExpViewerCreator creator;
	private JExpTableViewer viewer;
	private String title;
	private Object selectElement;

	public JExpDialogLookup(Shell parentShell, JExpViewerCreator creator,
			String title) {
		super(parentShell);
		this.creator = creator;
		this.title = title;
	}

	public Object getSelectElement() {
		return selectElement;
	}

	@Override
	protected void configureShell(Shell newShell) {
		super.configureShell(newShell);
		newShell.setText(title);
		newShell.setImage(JExpImageLink.getImage(JExpImageLink.LOOKUP));
		newShell.setSize(800, 600);
	}

	@Override
	protected Control createDialogArea(Composite parent) {
		Composite composite = new Composite(parent, SWT.NONE);
		composite.setLayout(new GridLayout(2, false));
		composite.setLayoutData(JExpLayoutFactory.gdFillBoth());
		JExpSearchPanel searchPanel = new JExpSearchPanel(composite);
		viewer = creator.createViewer(composite);
		viewer.setLayoutData(JExpLayoutFactory.gdFillBothWithHorizontalSpan(2));
		viewer.setInput(creator.getBeanModel());
		viewer.addDoubleClickListener(new IDoubleClickListener() {
			@Override
			public void doubleClick(DoubleClickEvent event) {
				okPressed();
			}
		});
		searchPanel.setViewer(viewer);
		return composite;
	}

	@Override
	protected void createButtonsForButtonBar(Composite parent) {
		createButton(parent, IDialogConstants.OK_ID,
				JExpSupplyMessages.Global_button_choose, true);
		createButton(parent, IDialogConstants.CANCEL_ID,
				JExpSupplyMessages.Global_button_cancel, false);
	}

	@Override
	protected boolean isResizable() {
		return true;
	}

	@Override
	protected void okPressed() {
		selectElement = viewer.getStructuredSelection().getFirstElement();
		super.okPressed();
	}
}
